package org.linlinjava.litemall.wx.util;

//import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.linlinjava.litemall.core.config.WxProperties;
import org.linlinjava.litemall.wx.dto.WxBaseLoginInfo;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;

import static net.sf.json.JSONObject.*;

public class WxDecrypt {
    public static String parseSessionKey(String result) {

        // 解析 JSON 数据获取 sessionKey
        int startIndex = result.indexOf("\"session_key\":\"") + "\"session_key\":\"".length();
        int endIndex = result.indexOf("\"", startIndex);
        return result.substring(startIndex, endIndex);
    }
    //解析电话号码
    public static Object getPhoneNumber(WxBaseLoginInfo vxVo) {
        // 修正：先获取 Base64.Decoder 对象，再调用 decode 方法进行解码
        byte[] dataByte = Base64.getDecoder().decode(vxVo.getCode());
        byte[] keyByte = Base64.getDecoder().decode(vxVo.getEncryptedData());
        byte[] ivByte = Base64.getDecoder().decode(vxVo.getIv());
        try {
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
//                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
